"""
{
    "ocr.language": {
        "title": "语言/模型库",
        "optionsList": [
            ["models/config_chinese.txt","简体中文"],
            ["models/config_en.txt","English"],
            ["models/config_chinese_cht(v2).txt","繁體中文"],
            ["models/config_japan.txt","日本語"],
            ["models/config_korean.txt","한국어"],
            ["models/config_cyrillic.txt","Русский"]
        ],
        "type": "enum",
        "default": "models/config_chinese.txt"
    },
    "ocr.cls": {
        "title": "纠正文本方向",
        "default": false,
        "toolTip": "启用方向分类，识别倾斜或倒置的文本。可能降低识别速度。",
        "type": "boolean"
    },
    "ocr.limit_side_len": {
        "title": "限制图像边长",
        "optionsList": [
            [960,"960 （默认）"],
            [2880,"2880"],
            [4320,"4320"],
            [999999,"无限制"]
        ],
        "toolTip": "将边长大于该值的图片进行压缩，可以提高识别速度。可能降低识别精度。",
        "type": "enum",
        "default": 960
    },
    "tbpu.parser": {
        "title": "排版解析方案",
        "toolTip": "按什么方式，解析和排序图片中的文字块",
        "default": "multi_para",
        "optionsList": [
            ["multi_para","多栏-按自然段换行"],
            ["multi_line","多栏-总是换行"],
            ["multi_none","多栏-无换行"],
            ["single_para","单栏-按自然段换行"],
            ["single_line","单栏-总是换行"],
            ["single_none","单栏-无换行"],
            ["single_code","单栏-保留缩进"],
            ["none","不做处理"]
        ],
        "type": "enum"
    },
    "tbpu.ignoreArea": {
        "title": "忽略区域",
        "toolTip": "数组，每一项为[[左上角x,y],[右下角x,y]]。",
        "default": [],
        "type": "var"
    },
    "tbpu.ignoreRangeStart": {
        "title": "忽略区域起始",
        "toolTip": "忽略区域生效的页数范围起始。从1开始。",
        "default": 1,
        "type": "number",
        "isInt": true
    },
    "tbpu.ignoreRangeEnd": {
        "title": "忽略区域结束",
        "toolTip": "忽略区域生效的页数范围结束。可以用负数表示倒数第X页。",
        "default": -1,
        "type": "number",
        "isInt": true
    },
    "pageRangeStart": {
        "title": "OCR页数起始",
        "toolTip": "OCR的页数范围起始。从1开始。",
        "default": 1,
        "type": "number",
        "isInt": true
    },
    "pageRangeEnd": {
        "title": "OCR页数结束",
        "toolTip": "OCR的页数范围结束。可以用负数表示倒数第X页。",
        "default": -1,
        "type": "number",
        "isInt": true
    },
    "pageList": {
        "title": "OCR页数列表",
        "toolTip": "数组，可指定单个或多个页数。例：[1,2,5]表示对第1、2、5页进行OCR。如果与页数范围同时填写，则 pageList 优先。",
        "default": [],
        "type": "var"
    },
    "password": {
        "title": "密码",
        "toolTip": "如果文档已加密，则填写文档密码。",
        "default": "",
        "type": "text"
    },
    "doc.extractionMode": {
        "title": "内容提取模式",
        "toolTip": "若一页文档既存在图片又存在文本，如何进行处理。",
        "default": "mixed",
        "optionsList": [
            ["mixed","混合OCR/原文本"],
            ["fullPage","整页强制OCR"],
            ["imageOnly","仅OCR图片"],
            ["textOnly","仅拷贝原有文本"]
        ],
        "type": "enum"
    }
}
"""

import os
import json
import requests
import time

def step_1_upload(path):
    url = "http://127.0.0.1:8282/api/doc/upload"
    options_json = json.dumps(
        {
            "doc.extractionMode": "textOnly",
        }
    )
    with open(path, "rb") as file:
        response = requests.post(url, files={"file": file}, data={"json": options_json})
    response.raise_for_status()
    res_data = json.loads(response.text)
    if res_data["code"] == 101:
        file_name = os.path.basename(path)
        file_prefix, file_suffix = os.path.splitext(file_name)
        temp_name = "temp" + file_suffix
        print("[Warning] Detected file upload failure: code == 101")
        print(
            "Attempting to use temp_name",
            temp_name,
            "instead of the original file_name",
            file_name,
        )
        with open(path, "rb") as file:
            response = requests.post(
                url,
                files={"file": (temp_name, file)},
                data={"json": options_json},
            )
        response.raise_for_status()
        res_data = json.loads(response.text)
    assert res_data["code"] == 100, "Task submission failed: {}".format(res_data)
    print(res_data)
    task_id = res_data["data"]
    return task_id

def step_2_ocr(task_id):
    url = "http://127.0.0.1:8282/api/doc/result"
    headers = {"Content-Type": "application/json"}
    data_str = json.dumps(
        {
            "id": task_id,
            "is_data": True,
            "format": "text",
            "is_unread": True,
        }
    )
    while True:
        time.sleep(1)
        response = requests.post(url, data=data_str, headers=headers)
        response.raise_for_status()
        res_data = json.loads(response.text)
        assert res_data["code"] == 100, "Failed to get task status: {}".format(res_data)
        if res_data["is_done"]:
            state = res_data["state"]
            assert state == "success", "Task execution failed: {}".format(res_data["message"])
            print("OCR task completed.")
            return res_data["data"]

def main():
    path = 'c:/Tmp/credit/2025011520400606987578.pdf'
    task_id = step_1_upload(path)
    result = step_2_ocr(task_id)
    print(result)

if __name__ == "__main__":
    main()







